package ch02.demo;

import org.junit.After;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Add {
    Document doc=null;
    @Test
    public void addNode() throws ParserConfigurationException, IOException, SAXException {
        System.out.println("添加节点信息");
        DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
        DocumentBuilder db=factory.newDocumentBuilder();
        doc =db.parse("src/main/java/ch02/demo/Parse.xml");
        Element select=doc.createElement("select");
        select.setAttribute("id","getCount");
        select.setTextContent("select count(id) from t_user");
        Node mapper=doc.getElementsByTagName("PhoneInfo").item(0);
        Element e= (Element) mapper;
        System.out.println("节点添加成功");
    }
    @After
    public void destory() throws TransformerException, FileNotFoundException {
        TransformerFactory fac=TransformerFactory.newInstance();
        Transformer transformer=fac.newTransformer();
        DOMSource source=new DOMSource(doc);

        transformer.setOutputProperty(OutputKeys.ENCODING,"utf-8");
        StreamResult res=new StreamResult(new FileOutputStream("src/main/java/ch02/demo/Parse.xml"));
        transformer.transform(source,res);
    }
}
